/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package UI.bll;

import BLL.establishTables;
import BLL.homepage;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.io.File;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Random;

/**
 * @author YELIUHUISHI
 */
public class Homepage extends javax.swing.JFrame {

    boolean flagSeek=false;
    Thread searchThread =new Thread();
    Thread timeThread =new Thread();

    /**
     * Creates new form homepage
     */
    public Homepage() {
        initComponents();
        init();
    }

    private void init() {
        new establishTables().inspectStudent();
        this.setTitle("主页界面");
        this.setResizable(false);
        homepage homepage = new homepage();
        renewal(homepage.all());
        uiutlLogin uiutlLogin = new uiutlLogin();
        uiutlLogin.setFrameConter(this);
        uiutlLogin.setFrameTmage(this, "src" + File.separator + "UI" + File.separator + "icon" + File.separator + "Homepage.jpg");

        timeThread = new Thread(new runnableTime(this.Time));


        searchThread=new Thread(() -> {
            while (true) {
                String text = homepageSeek.getText();
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String text1 = homepageSeek.getText();
                if (!text1.equals(text) || flagSeek) {
                    ResultSet resultSet = homepage.singleLog(homepageSeek.getText());
                    if (resultSet != null) {
                        renewal(resultSet);
                    }

                    flagSeek = false;
                }
            }
        });
        timeThread.start();
        searchThread.start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        homepageSeek = new javax.swing.JTextField();
        homepageFine = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        homepagetForm = new javax.swing.JTable();
        hompageAdd = new javax.swing.JButton();
        hompageDelete = new javax.swing.JButton();
        homepageUpdate = new javax.swing.JButton();
        homepageExit = new javax.swing.JButton();
        Time = new javax.swing.JLabel();

        Time.setFont(new java.awt.Font("宋体", 0, 18)); // NOI18N
        Time.setForeground(new java.awt.Color(255, 20, 18));
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        homepageSeek.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                homepageFineActionPerformed(evt);
            }
        });

        homepageFine.setText("查找");
        homepageFine.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                homepageFineActionPerformed(evt);
            }
        });


        homepagetForm.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null},
                        {null, null, null, null}
                },
                new String[]{
                        "id", "name", "sex", "age"
                }
        ));
        jScrollPane1.setViewportView(homepagetForm);

        hompageAdd.setText("添加");
        hompageAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hompageAddActionPerformed(evt);
            }
        });

        hompageDelete.setText("删除");
        hompageDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hompageDeleteActionPerformed(evt);
            }
        });

        homepageUpdate.setText("修改");
        homepageUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                homepageUpdateActionPerformed(evt);
            }
        });

        homepageExit.setText("退出");
        homepageExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                homepageExitActionPerformed(evt);
            }
        });
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(20, 20, 20)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(20, 20, 20)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addComponent(hompageAdd)
                                                        .addComponent(hompageDelete)
                                                        .addComponent(homepageUpdate)
                                                        .addComponent(homepageExit)))
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(homepageSeek, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(20, 20, 20)
                                                .addComponent(homepageFine)
                                                .addGap(50, 50, 50)
                                                .addComponent(Time, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                .addGap(0, 26, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGap(20, 20, 20)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(homepageSeek, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(homepageFine, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(Time, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(20, 20, 20)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(hompageAdd)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(hompageDelete)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(homepageUpdate)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(homepageExit)))
                                .addContainerGap(20, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //添加键的动作事件
    private void hompageAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hompageAddActionPerformed
        timeThread.stop();
        searchThread.stop();
        new Add().setVisible(true);
        this.dispose();
    }//GEN-LAST:event_hompageAddActionPerformed

    //删除键的动作事件
    private void hompageDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hompageDeleteActionPerformed
        int selectedRow = homepagetForm.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "未选择需要的");
            return;
        }
        int id = (int) homepagetForm.getValueAt(selectedRow, 0);
        int i = JOptionPane.showConfirmDialog(null, "是否删除？", null, JOptionPane.YES_NO_OPTION);
        if (i == 0) {
            homepage homepage = new homepage();
            boolean delete = homepage.delete(id);
            if (delete) {
                JOptionPane.showMessageDialog(this, "删除失败");
            } else {
                JOptionPane.showMessageDialog(this, "删除成功");
            }
        }
        flagSeek=true;

    }//GEN-LAST:event_hompageDeleteActionPerformed

    //修改键的动作事件
    private void homepageUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_homepageUpdateActionPerformed
        int selectedRow = homepagetForm.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "未选择需要的");
            return;
        }
        int id = (int) homepagetForm.getValueAt(selectedRow, 0);
        timeThread.stop();
        searchThread.stop();
        new Update(id).setVisible(true);
        this.dispose();

    }//GEN-LAST:event_homepageUpdateActionPerformed

    //查找键的动作事件
    private void homepageFineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_homepageFineActionPerformed
        String text = homepageSeek.getText();

        homepage homepage = new homepage();
        ResultSet resultSet = homepage.singleLog(text);
        if(resultSet!=null){
            renewal(resultSet);
        }
    }//GEN-LAST:event_homepageFineActionPerformed

    //退出键的动作事件
    private void homepageExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_homepageFineActionPerformed
        timeThread.stop();
        searchThread.stop();
        this.dispose();
        ProgressMonitor progressMonitor = new ProgressMonitor(this, null, "数据保存中....", 0, 100);
        progressMonitor.getNote();
        Random random = new Random();
        new Thread(() -> {
            for (int i = 0; i < 101; i += random.nextInt(20)) {
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                progressMonitor.setProgress(i);

            }
            progressMonitor.setProgress(100);

            System.exit(0);
        }).start();


        // TODO add your handling code here:
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton homepageExit;
    public javax.swing.JButton homepageFine;
    public javax.swing.JTextField homepageSeek;
    public javax.swing.JButton homepageUpdate;
    public javax.swing.JTable homepagetForm;
    public javax.swing.JButton hompageAdd;
    public javax.swing.JButton hompageDelete;
    public javax.swing.JLabel Time;
    public javax.swing.JScrollPane jScrollPane1;

    private void renewal(ResultSet all) {
        homepage homepage = new homepage();

        Object[][] objects = {};
        String[] strings = {"id", "name", "sex", "age"};
        DefaultTableModel defaultTableModel = new DefaultTableModel(objects, strings);
        homepagetForm.setModel(defaultTableModel);

        try {
            while (all.next()) {
                Object[] objects1 = {
                        all.getInt("id"),
                        all.getString("name"),
                        all.getString("sex"),
                        all.getInt("age")
                };
                defaultTableModel.addRow(objects1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}
